package com.yuanfeng.goods.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.yuanfeng.commoms.dto.goods.GoodsListQueryEsDTO;
import com.yuanfeng.commoms.dto.goods.GoodsMerchantSearchWordDTO;
import com.yuanfeng.commoms.dto.goods.ShopListQueryDTO;
import com.yuanfeng.commoms.dto.goods.WebGoodsListQueryDTO;
import com.yuanfeng.commoms.dto.shop.*;
import com.yuanfeng.commoms.util.Json.JsonUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.PinyinUtils;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.goods.feign.BaseServiceClient;
import com.yuanfeng.goods.feign.BusinessServiceClient;
import com.yuanfeng.goods.mapper.GoodsBaseMapper;
import com.yuanfeng.goods.mapper.GoodsCommonAttributeAssociationMapper;
import com.yuanfeng.goods.mapper.GoodsCommonMapper;
import com.yuanfeng.goods.service.ElasticSearchService;
import com.yuanfeng.goods.util.es.ESUtils;
import io.seata.common.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ElasticSearchServiceImpl implements ElasticSearchService {
    @Autowired
    private GoodsBaseMapper goodsBaseMapper;

    @Autowired
    private GoodsCommonMapper goodsCommonMapper;

    @Autowired
    private BusinessServiceClient businessClient;

    @Autowired
    private ElasticSearchService elasticSearchService;

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    private BaseServiceClient baseServiceClient;

    @Autowired
    private GoodsCommonAttributeAssociationMapper goodsCommonAttributeAssociationMapper;


    @Override
    public List<ArticleDTO> selectAll() {
        List<ArticleDTO> articleDTOS = goodsBaseMapper.selectAll();
        return articleDTOS;
    }

    @Override
    public GoodsListQueryEsDTO selectByCommonId(Integer commonId) {
        return goodsBaseMapper.selectByCommonIdEs(commonId);
    }

    @Override
    public GoodsListQueryEsDTO selectByGoodsId(Integer goodsId) {
        return goodsBaseMapper.selectByGoodsIdEs(goodsId);
    }

    @Override
    public GoodsListQueryEsDTO selectShopIdByCommonId(Integer commonId) {
        return goodsCommonMapper.selectShopIdByCommonId(commonId);
    }

    @Override
    public List<ArticleShopDTO> selectAllShop() {
        return businessClient.selectAllShop();
    }

    @Override
    public List<WebShopListQueryEsDTO> selectByShopId(Integer shopId) {
        WebShopListQueryEsDTO webShopListQueryResult = null;
        List<WebShopListQueryEsDTO> shopList = new ArrayList<>();
        webShopListQueryResult = businessClient.selectByShopId2(shopId);
        if (null != webShopListQueryResult) {
            // 获取店铺导航
            List<MerchantShopNavQueryDTO> shopNav = businessClient.selectShopNav(shopId);

            // 获取店铺默认值
            getShopDefaultValue2(webShopListQueryResult);
            // 查询店铺商品
            List<GoodsListQueryEsDTO> commonList = goodsCommonMapper.selectByShopId3(shopId);
            webShopListQueryResult.setCommonList(commonList);
            // 查询店铺商品数量
            Integer shopGoodsSum = goodsCommonMapper.selectShopSum(shopId);
            webShopListQueryResult.setShopNav(shopNav);
            webShopListQueryResult.setShopGoodsSum(shopGoodsSum);
            shopList.add(webShopListQueryResult);
        }
        return shopList;
    }

    public void getShopDefaultValue2(WebShopListQueryEsDTO shopListQueryResult) {
        String configValue = null;
        ShopConfigDefaultValueDTO shopConfig = null;
        if (null != shopListQueryResult.getShopSlide() && !shopListQueryResult.getShopSlide().equals("")) {
            shopListQueryResult.setShopSlide(shopListQueryResult.getShopSlide().split(",", -1)[0]);
        } else {
            configValue = baseServiceClient.selectConfigValueFeign("shop_default_config");
            shopConfig = JsonUtils.string2Obj(configValue, ShopConfigDefaultValueDTO.class);
            shopListQueryResult.setShopSlide(shopConfig.getShopSlide().split(",", -1)[0]);
        }

        if (shopListQueryResult.getShopLogo() == null || shopListQueryResult.getShopLogo().equals("")) {
            if (shopConfig == null) {
                configValue = baseServiceClient.selectConfigValueFeign("shop_default_config");
                shopConfig = JsonUtils.string2Obj(configValue, ShopConfigDefaultValueDTO.class);
            }
            shopListQueryResult.setShopLogo(shopConfig.getShopLogo());
        }
    }
    @Override
    public ShopListQueryDTO selectByH5ShopId(Integer shopId) {
        ShopListQueryDTO shopListQueryDto = businessClient.selectByH5ShopId(shopId);
        if (null != shopListQueryDto) {
            // 获取店铺默认值
            String configValue = null;
            ShopConfigDefaultValueDTO shopConfig = null;
            if (null != shopListQueryDto.getShopSlide() && !shopListQueryDto.getShopSlide().equals("")) {
                shopListQueryDto.setShopSlide(shopListQueryDto.getShopSlide().split(",", -1)[0]);
            } else {
                configValue = baseServiceClient.selectConfigValueFeign("shop_default_config");
                shopConfig = JsonUtils.string2Obj(configValue, ShopConfigDefaultValueDTO.class);
                shopListQueryDto.setShopSlide(shopConfig.getShopSlide().split(",", -1)[0]);
            }

            if (shopListQueryDto.getShopLogo() == null || shopListQueryDto.getShopLogo().equals("")) {
                if (shopConfig == null) {
                    configValue = baseServiceClient.selectConfigValueFeign("shop_default_config");
                    shopConfig = JsonUtils.string2Obj(configValue, ShopConfigDefaultValueDTO.class);
                }
                shopListQueryDto.setShopLogo(shopConfig.getShopLogo());
            }
            List<Map<String, Object>> maps = goodsCommonMapper.selectuniappQueryShopGoods(shopListQueryDto);
            shopListQueryDto.setGoods(maps);
        }
        return shopListQueryDto;
    }

    @Override
    public ResponseResult pcSeachGoodsData(WebGoodsListQueryDTO webGoodsListQueryParam) {
        //查询plus是否开启
        Integer selectplus = (Integer) baseServiceClient.queryMerchantPlusRule().getData();
        Map<String, Object> resultMap = null;
        List<GoodsListQueryEsDTO> result = new ArrayList<>();
        try {
            resultMap = new HashMap<>();
            String token = webGoodsListQueryParam.getToken();
            Integer plusMember = null;
            BigDecimal plusDiscount = null;
            if (token != null){
                UserInfoVO userInfo = ParseTokenUtils.getUserInfoByTokenNoIsExist(token);
                if (userInfo != null) {
                    plusMember = userInfo.getPlusMember();
                    plusDiscount = userInfo.getPlusDiscount();
                }
            }

            GoodsListQueryEsDTO gdsListQueryResult =null;
            List<Integer> list2 = new ArrayList<>();

            //从es中查询数据
            Map<String, Object> map = ESUtils.pcSeachGoodsData(webGoodsListQueryParam);
            // 添加热搜词
            setHotSearchWords(webGoodsListQueryParam.getCommonName());
            ArrayList<ArticleDTO>  list = (ArrayList<ArticleDTO>)map.get("list");
            if(null != list && !list.isEmpty()){
                for (ArticleDTO articleDto : list) {
                    //根据前缀+CommonId从redis 中查询，如果存在将结果添加到返回值中，如果redis中不存在就从mysql中查询，将结果存入redis和返回值中
                    String jsonString = RedisUtil.get("yuanfeng_pc_goods_commonId_" + articleDto.getCommonId().toString());
                    if(null == jsonString){
                        gdsListQueryResult = elasticSearchService.selectByCommonId(articleDto.getCommonId());
                        if(null == gdsListQueryResult){
                            list2.add(articleDto.getCommonId());
                            continue;
                        }
                        //替换高亮商品名称
                        gdsListQueryResult.setCommonName(articleDto.getCommonName());
                        gdsListQueryResult.setPlusMember(plusMember);
                        gdsListQueryResult.setPlusDiscount(plusDiscount);
                        result.add(gdsListQueryResult);
                        RedisUtil.set("yuanfeng_pc_goods_commonId_" + articleDto.getCommonId(), JsonUtils.toString(gdsListQueryResult),60*60*24);//1天后过期
                    }else{
                        gdsListQueryResult = objectMapper.readValue(jsonString, GoodsListQueryEsDTO.class);
                        //替换高亮商品名称
                        gdsListQueryResult.setCommonName(articleDto.getCommonName());
                        gdsListQueryResult.setPlusMember(plusMember);
                        gdsListQueryResult.setPlusDiscount(plusDiscount);
                        result.add(gdsListQueryResult);
                    }
                }
                if(!list2.isEmpty()){
                    ESUtils.delete(list2);
                }


                resultMap.put("list",result);
                resultMap.put("plusStatus",selectplus);
                resultMap.put("totalCount",map.get("count"));
                resultMap.put("goodsBrandCatParam",map.get("goodsBrandCatParam"));
                resultMap.put("gdbGoodsAttParams",map.get("gdbGoodsAttParams"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (CollectionUtils.isEmpty(result)){
            result=Lists.newArrayList();
            resultMap.put("list",result);
            resultMap.put("plusStatus",selectplus);
            resultMap.put("totalCount",0);
            resultMap.put("goodsBrandCatParam",null);
            resultMap.put("goodsAttributeResults",null);
        }
        return ResponseResult.success(resultMap);
    }

    @Override
    public ResponseResult pcSeachShopData(WebShopListQueryDTO webGoodsListQueryParam) {
        //查询plus是否开启
        Integer selectplus = (Integer) baseServiceClient.queryMerchantPlusRule().getData();
        Map<String, Object> resultMap = null;
        try {
            resultMap = new HashMap<>();
            List<WebShopListQueryEsDTO> result = new ArrayList<>();
            List<WebShopListQueryEsDTO> webShopListQueryResults =null;

            String token = webGoodsListQueryParam.getToken();
            Integer plusMember = null;
            BigDecimal plusDiscount = null;
            if (token != null){
                UserInfoVO userInfo = ParseTokenUtils.getUserInfoByTokenNoIsExist(token);
                if (userInfo != null) {
                    plusMember = userInfo.getPlusMember();
                    plusDiscount = userInfo.getPlusDiscount();
                }
            }

            List<Integer> list2 = new ArrayList<>();

            //从es中查询数据
            Map<String, Object> map = ESUtils.pcSeachShopData(webGoodsListQueryParam);
            ArrayList<ArticleShopDTO>  list = (ArrayList<ArticleShopDTO>)map.get("list");
            if(null != list && !list.isEmpty()){
                for (ArticleShopDTO articleShopDto : list) {
                    //根据前缀+CommonId从redis 中查询，如果存在将结果添加到返回值中，如果redis中不存在就从mysql中查询，将结果存入redis和返回值中
                    String jsonString = RedisUtil.get("yuanfeng_pc_shop_shopId_" + articleShopDto.getShopId().toString());
                    if(null == jsonString){
                        webShopListQueryResults = elasticSearchService.selectByShopId(articleShopDto.getShopId());
                        if(null == webShopListQueryResults || webShopListQueryResults.size() == 0){
                            list2.add(articleShopDto.getShopId());
                            continue;
                        }
                        webShopListQueryResults.get(0).setShopName(articleShopDto.getShopName());
                        webShopListQueryResults.get(0).setPlusMember(plusMember);
                        webShopListQueryResults.get(0).setPlusDiscount(plusDiscount);
                        result.add(webShopListQueryResults.get(0));
                        RedisUtil.set("yuanfeng_pc_shop_shopId_" + articleShopDto.getShopId(), JsonUtils.toString(webShopListQueryResults.get(0)),60*60*24);//1天后过期
                    }else{
                        WebShopListQueryEsDTO webShopListQueryResult = objectMapper.readValue(jsonString, WebShopListQueryEsDTO.class);
                        webShopListQueryResult.setShopName(articleShopDto.getShopName());
                        webShopListQueryResult.setPlusMember(plusMember);
                        webShopListQueryResult.setPlusDiscount(plusDiscount);
                        result.add(webShopListQueryResult);
                    }
                }
                if(null != list2 && 0 != list2.size()){
                    ESUtils.deleteShop(list2);
                }
                resultMap.put("list",result);
                resultMap.put("plusStatus",selectplus);
                resultMap.put("totalCount",map.get("count"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(resultMap);
    }


    private void setHotSearchWords(String commonName) {
        if (null != commonName && !commonName.equals("")) {
            GoodsMerchantSearchWordDTO searchWord = baseServiceClient.queryHotSearchWords(commonName);
            GoodsMerchantSearchWordDTO record = new GoodsMerchantSearchWordDTO();
            if (null != searchWord && !searchWord.equals("")) {
                searchWord.setSearchNums(searchWord.getSearchNums() + 1);
                baseServiceClient.updateHotSearchWords(searchWord);
            } else {
                record.setSearchKeyword(commonName);
                record.setSearchCharIndex(PinyinUtils.ToPinyin(commonName));
                record.setSearchNums(1);
                baseServiceClient.addHotSearchWords(record);
            }
        }
    }

    @Override
    public ResponseResult createGoodsIndex() {
        return ESUtils.setMappings();
    }

    @Override
    public ResponseResult createShopIndex() {
        return ESUtils.setShopMappings();
    }

    @Override
    public ResponseResult deleteGoodsIndex() {
        return ESUtils.deleteGoodsIndex();
    }

    @Override
    public ResponseResult deleteShopIndex() {
        return ESUtils.deleteShopIndex();
    }

    @Override
    public ResponseResult importData() {
        List<ArticleDTO> articleDTOS = goodsBaseMapper.selectAll();
        if(null != articleDTOS && !articleDTOS.isEmpty()){
            //查询商品的属性内容 将商品每个属性内容用 - -前后包裹，拼接成用 逗号 分割 的string 存入 es
            for (ArticleDTO articleDto : articleDTOS) {
                String strAttributeContentIds = null;
                List<String> attributeContentIds= goodsCommonAttributeAssociationMapper.queryGoodsAttributeContent(articleDto.getCommonId());
                if(null != attributeContentIds && !attributeContentIds.isEmpty()){
                    for (String attributeContentId : attributeContentIds) {
                        attributeContentId = "-" +attributeContentId +"-,";
                        if(null == strAttributeContentIds){
                            strAttributeContentIds = attributeContentId;
                        }else{
                            strAttributeContentIds = strAttributeContentIds + attributeContentId;
                        }
                    }
                    articleDto.setAttributeContentId(strAttributeContentIds);
                }
            }
        }
        return ESUtils.importData(articleDTOS);
    }

    @Override
    public ResponseResult importShopData() {
        List<ArticleShopDTO> articleShopDto = businessClient.selectAllShop();
        return ESUtils.importShopData(articleShopDto);
    }

    @Override
    public ResponseResult deleteGoodsData() {
        return ESUtils.deleteAll();
    }

    @Override
    public ResponseResult deleteShopData() {
        return ESUtils.deleteShopAll();
    }

    @Override
    public ResponseResult h5SeachGoodsData(WebGoodsListQueryDTO webGoodsListQueryParam) {
        Map<String, Object> resultMap = null;
        try {
            resultMap = new HashMap<>();
            List<GoodsListQueryEsDTO> result = new ArrayList<>();
            GoodsListQueryEsDTO gdsListQueryResult =null;
            List<Integer> list2 = new ArrayList<>();

            //从es中查询数据
            Map<String, Object> map = ESUtils.h5SeachGoodsData(webGoodsListQueryParam);
            // 添加热搜词
            setHotSearchWords(webGoodsListQueryParam.getCommonName());
            List<ArticleDTO>  list = (List<ArticleDTO>)map.get("list");
            if(null != list && !list.isEmpty()){
                for (ArticleDTO articleDto : list) {
                    //根据前缀+CommonId从redis 中查询，如果存在将结果添加到返回值中，如果redis中不存在就从mysql中查询，将结果存入redis和返回值中
                    //String jsonString = RedisUtil.get("yuanfeng_h5_goods_commonId_" + articleDto.getCommonId().toString());
                    String jsonString = null;
                    if(null == jsonString){
                        gdsListQueryResult = elasticSearchService.selectByCommonId(articleDto.getCommonId());
                        if(null == gdsListQueryResult){
                            list2.add(articleDto.getCommonId());
                            continue;
                        }
                        gdsListQueryResult.setCommonNameOrignial(gdsListQueryResult.getCommonName());
                        //替换高亮商品名称
                        gdsListQueryResult.setCommonName(articleDto.getCommonName());
                        result.add(gdsListQueryResult);
                        RedisUtil.set("yuanfeng_h5_goods_commonId_" + articleDto.getCommonId(), JsonUtils.toString(gdsListQueryResult),60*60*24);//1天后过期
                    }else{
                        gdsListQueryResult = objectMapper.readValue(jsonString, GoodsListQueryEsDTO.class);
                        //替换高亮商品名称
                        gdsListQueryResult.setCommonName(articleDto.getCommonName());
                        result.add(gdsListQueryResult);
                    }
                }
                if(!list2.isEmpty()){
                    ESUtils.delete(list2);
                }
                resultMap.put("list",result);
                resultMap.put("totalCount",map.get("count"));
                resultMap.put("goodsBrandCatParam",map.get("goodsBrandCatParam"));
                resultMap.put("goodsAttributeResults",map.get("gdbGoodsAttParams"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(resultMap);
    }

    @Override
    public ResponseResult h5SeachShopData(ShopListQueryDTO shopListQueryParam) {
        Map<String, Object> resultMap = null;
        try {
            resultMap = new HashMap<>();
            List<ShopListQueryDTO> result = new ArrayList<>();
            ShopListQueryDTO shopListQueryDto =null;
            List<Integer> list2 = new ArrayList<>();

            //从es中查询数据
            Map<String, Object> map = ESUtils.h5SeachShopData(shopListQueryParam);
            ArrayList<ArticleShopDTO>  list = (ArrayList<ArticleShopDTO>)map.get("list");
            if(null != list && !list.isEmpty()){
                for (ArticleShopDTO articleShopDto : list) {
                    //根据前缀+shop_id从redis 中查询，如果存在将结果添加到返回值中，如果redis中不存在就从mysql中查询，将结果存入redis和返回值中
//                    String jsonString = RedisUtil.get("yuanfeng_h5_shop_shopId_" + articleShopDto.getShopId().toString());
                    String jsonString = null;
                    if(null == jsonString){
                        shopListQueryDto = elasticSearchService.selectByH5ShopId(articleShopDto.getShopId());
                        if(null == shopListQueryDto){
                            list2.add(articleShopDto.getShopId());
                            continue;
                        }
                        shopListQueryDto.setShopName(articleShopDto.getShopName());
                        result.add(shopListQueryDto);
                        RedisUtil.set("yuanfeng_h5_shop_shopId_" + articleShopDto.getShopId(), JsonUtils.toString(shopListQueryDto),60*60*24);//1天后过期
                    }else{
                        ShopListQueryDTO webShopListQueryDTO = objectMapper.readValue(jsonString, ShopListQueryDTO.class);
                        webShopListQueryDTO.setShopName(articleShopDto.getShopName());
                        result.add(webShopListQueryDTO);
                    }
                }
                if(!list2.isEmpty()){
                    ESUtils.deleteShop(list2);
                }
                resultMap.put("list",result);
                resultMap.put("totalCount",map.get("count"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(resultMap);
    }

    @Override
    public ResponseResult querySeachBrandAttributeData(WebGoodsListQueryDTO webGoodsListQueryParam) {
        Map<String, Object> seachBrandAttributeMap = ESUtils.querySeachBrandAttributeData(webGoodsListQueryParam);
        return ResponseResult.success(seachBrandAttributeMap);
    }

}
